/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.deployer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.deploy.DeploymentCache;
import com.je.bpm.engine.impl.persistence.deploy.DeploymentManager;
import com.je.bpm.engine.impl.persistence.deploy.ProcessDefinitionCacheEntry;
import com.je.bpm.engine.impl.persistence.deploy.ProcessDefinitionInfoCacheObject;
import com.je.bpm.engine.impl.persistence.entity.DeploymentEntity;
import com.je.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import com.je.bpm.core.model.process.Process;
import com.je.bpm.engine.impl.persistence.entity.ProcessDefinitionInfoEntity;
import com.je.bpm.engine.impl.persistence.entity.ProcessDefinitionInfoEntityManager;

/**
 * Updates caches and artifacts for a deployment, its process definitions,
 * and its process definition infos.
 */
public class CachingAndArtifactsManager {

    /**
     * Ensures that the process definition is cached in the appropriate places, including the
     * deployment's collection of deployed artifacts and the deployment manager's cache, as well
     * as caching any ProcessDefinitionInfos.
     */
    public void updateCachingAndArtifacts(ParsedDeployment parsedDeployment) {
        CommandContext commandContext = Context.getCommandContext();
        final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
        DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache
                = processEngineConfiguration.getDeploymentManager().getProcessDefinitionCache();
        DeploymentEntity deployment = parsedDeployment.getDeployment();

        for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
            BpmnModel bpmnModel = parsedDeployment.getBpmnModelForProcessDefinition(processDefinition);
            Process process = parsedDeployment.getProcessModelForProcessDefinition(processDefinition);
            ProcessDefinitionCacheEntry cacheEntry = new ProcessDefinitionCacheEntry(processDefinition, bpmnModel, process);
            processDefinitionCache.add(processDefinition.getId(), cacheEntry);
            addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);

            // Add to deployment for further usage
            deployment.addDeployedArtifact(processDefinition);
        }
    }

    protected void addDefinitionInfoToCache(ProcessDefinitionEntity processDefinition,
                                            ProcessEngineConfigurationImpl processEngineConfiguration, CommandContext commandContext) {

        if (!processEngineConfiguration.isEnableProcessDefinitionInfoCache()) {
            return;
        }

        DeploymentManager deploymentManager = processEngineConfiguration.getDeploymentManager();
        ProcessDefinitionInfoEntityManager definitionInfoEntityManager = commandContext.getProcessDefinitionInfoEntityManager();
        ObjectMapper objectMapper = commandContext.getProcessEngineConfiguration().getObjectMapper();
        ProcessDefinitionInfoEntity definitionInfoEntity = definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinition.getId());

        ObjectNode infoNode = null;
        if (definitionInfoEntity != null && definitionInfoEntity.getInfoJsonId() != null) {
            byte[] infoBytes = definitionInfoEntityManager.findInfoJsonById(definitionInfoEntity.getInfoJsonId());
            if (infoBytes != null) {
                try {
                    infoNode = (ObjectNode) objectMapper.readTree(infoBytes);
                } catch (Exception e) {
                    throw new ActivitiException("Error deserializing json info for process definition " + processDefinition.getId());
                }
            }
        }

        ProcessDefinitionInfoCacheObject definitionCacheObject = new ProcessDefinitionInfoCacheObject();
        if (definitionInfoEntity == null) {
            definitionCacheObject.setRevision(0);
        } else {
            definitionCacheObject.setId(definitionInfoEntity.getId());
            definitionCacheObject.setRevision(definitionInfoEntity.getRevision());
        }

        if (infoNode == null) {
            infoNode = objectMapper.createObjectNode();
        }
        definitionCacheObject.setInfoNode(infoNode);

        deploymentManager.getProcessDefinitionInfoCache().add(processDefinition.getId(), definitionCacheObject);
    }
}
